<template>
  <div class="h-full w-full p-4">
    <div class="query-section">
      <el-form :model="queryForm" label-width="auto" class="w-full" style="">
        <el-row :gutter="10">
          <el-col :span="5">
            <el-form-item label="服务名称">
              <el-input v-model="queryForm.params.formName_like"
                        @clear="()=>{queryForm.params.formName_like=undefined}"
                        clearable placeholder="请输入"/>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="URL">
              <el-input v-model="queryForm.params.url_like"
                        @clear="()=>{queryForm.params.url_like=undefined}"
                        clearable placeholder="请输入"/>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="服务类型：">
              <el-select v-model="queryForm.params.serverType" clearable>
                <el-option v-for="item in [
                                            { label: '接口', value: 'InterfaceType' },
                                            { label: '定时任务', value: 'SchedulerType' },
                                            { value: 'VersionWatchTableType', label: '接口触发表监听' },
                                            { value: 'ApiWatchTableType', label: '版本触发表监听' },
                                            { value: 'ApiEnhanceType', label: '表单接口增强' },
                                          ]"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="发布状态">
              <el-select v-model="queryForm.params.status" clearable placeholder="请选择">
                <el-option v-for="item in ENABLE_OPTIONS"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="getTableDataList(1)">查询</el-button>
          </el-col>
          <!--          <el-col :span="4">-->
          <!--            <el-button type="primary">Primary</el-button>-->
          <!--            <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">-->
          <!--              <a-button type="primary">查询</a-button>-->
          <!--              <a-button style="margin-left: 8px">重置</a-button>-->
          <!--              <a @click="toggleAdvanced" style="margin-left: 8px">-->
          <!--                {{ advanced ? '收起' : '展开' }}-->
          <!--                <a-icon :type="advanced ? 'up' : 'down'"/>-->
          <!--              </a>-->
          <!--            </span>-->
          <!--          </el-col>-->
        </el-row>
      </el-form>
    </div>
    <div class="operation-section">
      <el-button type="primary" @click="doDesign">新增</el-button>
      <!--      <el-button type="primary">查询</el-button>-->
    </div>
    <div class="table-section mt-4">
      <el-table v-loading="tableLoading" :data="tableData.content" border style="width: 100%;--el-table-header-bg-color: #fafafa" max-height="650">
        <el-table-column type="index" label="#" width="50" fixed align="center"></el-table-column>
        <el-table-column label="服务名称" min-width="180" prop="name" show-overflow-tooltip></el-table-column>
        <el-table-column label="服务类型" width="150" prop="serverType"/>
        <el-table-column label="接口url" prop="url" show-overflow-tooltip width="220"/>
        <el-table-column label="定时表达式" prop="cron" show-overflow-tooltip width="140"/>
        <el-table-column label="状态" prop="status" width="70">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 'Enable'"
                    effect="plain"
                    size="small"
                    type="success">启用
            </el-tag>
            <el-tag v-if="scope.row.status === 'Disable'"
                    effect="plain"
                    size="small"
                    type="danger">停用
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="creationTime" align="center" width="180">
          <template #default="scope">
            {{ dayjs(scope.row.creationTime).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="210">
          <template #default="scope">
            <el-button link type="primary" size="small" @click.prevent="doPublish(scope.row)">编辑</el-button>
            <el-button link type="primary" size="small" @click.prevent="doPublish(scope.row)">授权</el-button>
            <el-button link type="primary" size="small" @click.prevent="doPublish(scope.row)" v-if="scope.row.status==='Disable'">启用</el-button>
            <el-button link type="primary" size="small" @click.prevent="doReclaim(scope.row)" v-if="scope.row.status==='Enable'">停用</el-button>
            <!-- 删除按钮加一个二次确认 -->
            <el-popconfirm class="box-item" title="确认要删除吗?" placement="bottom" @confirm.prevent="doDelete(scope.row)">
              <template #reference>
                <el-button link type="primary" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div class="mt-4 w-full flex justify-end">
        <el-pagination class=""
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"
                       :current-page="queryForm.page"
                       :page-sizes="[10, 20, 30, 50, 100]"
                       :page-size="queryForm.size"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="tableData.totalElements">
        </el-pagination>
      </div>
    </div>
    <!--    <WorkflowEditor ref="workflowEditorRef"/>-->
  </div>
</template>

<script setup>
/////////////////////////////////   外部依赖导入    //////////////////////////
import {onMounted, onUnmounted, ref, reactive} from 'vue'
import {useRoute, useRouter} from 'vue-router';
import defaultLogo from "@/assets/images/default-logo.png";
import defaultAvatar from "@/assets/images/default-avatar.jpg";
import {$localStorage} from "@/utils/application-storage.js";
import $apiService from "@/axios/api.js";
import {ENABLE_OPTIONS, PUBLISH_OPTIONS} from "@/utils/constant.js";
import $message from "@/utils/message.js";
import dayjs from "dayjs";

// import WorkflowEditor from "./component/WorkflowEditor.vue";

/////////////////////////////////   私有变量定义    //////////////////////////
const $router = useRouter();
const $route = useRoute();

const tenantInfo = ref({
  id: "",
  logo: defaultLogo,
  tenantCode: '',
  systemName: ''
})
const myProfile = ref({
  avatarUrl: defaultAvatar,
  realName: ''
})
const queryForm = reactive({
  params: {
    tenantApplicationId: $route.params.applicationId,
  },
  page: 1,
  size: 10,
  sort: ['creationTime,desc'],
})
const tableData = reactive({
  content: [],
  totalElements: 1,
})
const workflowEditorRef = ref(null);
let tableLoading = ref(false)
const applicationList = ref([])

/////////////////////////////////   生命周期方法 //////////////////////////
onMounted(() => {
  tenantInfo.value = $localStorage.getTenantInfo()
  myProfile.value = $localStorage.getMyProfile()
  getTableDataList()
});
onUnmounted(() => {
});

/////////////////////////////////   页面方法    //////////////////////////
const getTableDataList = (page) => {
  if (page) queryForm.page = page
  tableLoading = true
  $apiService.getApiTransactorList(queryForm).then((res) => {
    tableData.content = res.data.data.content
    tableData.totalElements = res.data.data.totalElements
    tableLoading = false
  }).finally(() => {
    tableLoading = false
  })
}
const handleSizeChange = (newSize) => {
  queryForm.size = newSize;
  getTableDataList();
}
const handleCurrentChange = (newPage) => {
  queryForm.page = newPage;
  getTableDataList();
}
const doDesign = () => {
  workflowEditorRef.value.show()
}
const doPublish = ({id}) => {
  $apiService.saveCustomProcess({id, definitionStatus: 'Yes'}).then((res) => {
    $message.success('已发布')
    getTableDataList()
  })
}
const doReclaim = ({id}) => {
  $apiService.saveCustomProcess({id, definitionStatus: 'No'}).then((res) => {
    $message.success('已撤回')
    getTableDataList()
  })
}
const doDeploy = (row) => {
  if ((!row.definitionType || !row.definitionType === 'CustomPage') && !row.actualTableName) return $message.warning('请先到流程配置关联表编码')
  const data = {
    stringBPMN: row.original.data,
    actualTableName: row.actualTableName,
    processName: row.name,
    tenantId: row.tenantId,
    processKey: row.keyCode,
    customProcessDefinitionId: row.id,
  }
  $apiService.deployProcessDefinition(data).then((res) => {
    $message.success('流程部署成功')
    getTableDataList()
  })
}
const doIcon = () => {
}
const doConfig = () => {
}
const doCopy = () => {
}
const doDelete = ({id}) => {
  $apiService.deleteCustomProcess(id).then((res) => {
    $message.success('流程删除成功')
    if (tableData.content.length === 1) {
      queryForm.page--
      getTableDataList(queryForm.page)
    } else {
      getTableDataList()
    }
  })
}
</script>

<style scoped>
.dialog-body-class {
  padding: 0 !important;
}
</style>
